﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace MyNetwork
{
	class MyDelayHS
	{
        private long _ticksPerSecond = 0;
        private long _baseTime = 0;
        public MyDelayHS()
        {
            if (!QueryPerformanceFrequency(ref _ticksPerSecond))
                throw new ApplicationException("Timer: Performance Frequency Unavailable");
        }

        public void Clear()
        {
            _Started = false;
            Now();
        }

        private bool _Started = false;
        public bool Process(int ms)
        {
            if (_Started == false)
            {
                _Started = true;
                Now();
            }
            else
            {
                if (GetTimeMs() > ms)
                {
                    _Started = false;
                    return true;
                }
            }
            return false;
        }

        public long Now()
        {
            QueryPerformanceCounter(ref _baseTime);
            return _baseTime;
        }

        public double GetTimeMs()
        {
            long cur_time = 0;
            QueryPerformanceCounter(ref cur_time);
            double secs = (double)(cur_time - _baseTime) / (double)_ticksPerSecond;
            return (secs * 1000);
        }

        #region dll
        [DllImport("Kernel32.dll")]
        private static extern bool QueryPerformanceCounter(ref long lpPerformanceCount);
        [DllImport("Kernel32.dll")]
        private static extern bool QueryPerformanceFrequency(ref long lpFrequency);
        #endregion dll
    }
}
